<template>
  <div>
      <div>
        <div class="searchForm">
          <el-form :inline="true" :model="params" class="demo-form-inline">
            <el-form-item label="标题">
              <el-input 
                v-model="params.name"
                placeholder="按品牌名称查找"
                class="block"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                icon="el-icon-search"
                @click="getList(1)"
                class="block"
              >查询</el-button>
              <el-button
                icon="el-icon-plus"
                class="block"
                @click="add"
              >增加</el-button>
               <el-button
                type="danger"
                icon="el-icon-delete"
                class="block" 
                @click="removeMore"
              >批量删除</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div class="message">
           <el-table
            :data="rows"
            style="width: 100%"
            @selection-change="handleSelectionChange">
            >
            <el-table-column
              type="selection"
              width="55">
            </el-table-column>
            <el-table-column
              prop="name"
              label="品牌名称">
            </el-table-column>
            <el-table-column
              prop="img"
              label="logo">
            <template slot-scope="scope">
              <img style="width:40px;height:40px" v-if="scope.row.img" :src="scope.row.img"/>
            </template>  
            </el-table-column>
            <el-table-column
              label="操作">
              <template slot-scope="scope">
                <el-button 
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="edit(scope.row)"
                >编辑</el-button>
                <el-popconfirm
                   title = "确定删除此数据吗？"
                   @confirm="remove(scope.row)"
                >
                  <el-button icon="el-icon-delete" type="danger" style="margin-left: 20px;"
                  size="mini" slot="reference">删除</el-button>
                </el-popconfirm>

              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="pagination">
            <el-pagination
              @size-change="sizeChange"
              @current-change="getList"
              :current-page="params.pageNum"
              :page-sizes="[5,10,100, 200, 300, 400]"
              :page-size="params.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total">
            </el-pagination>
        </div>
      </div>
      <el-dialog :title="form._id ? '修改' :'新增'"  :visible.sync="dialogFormVisible"  :before-close="handleClose" width="400px">
      <el-form :model="form" ref="form" :rules="rules" label-width="100px">
        <el-form-item
          label="logo"
          prop="img"
          style="margin-bottom: 20px"
        >
          <div
            @click="openFile"
            style="
              width: 100px;
              height: 100px;
              font-size: 32px;
              border: 1px dashed #ccc;
              text-align: center;
              line-height: 100px;
              opacity: 0.5;
              overflow:hiddrn;
            "
          >
            <img style="max-width:100%;max-height:100%" v-if="form.img" :src="form.img"/>
            <span v-else>+</span>
          </div>
          <input
            ref="file"
            style="display: none"
            type="file"
            multiple
            accept="image/*"
            @change="changeFile"
          />
        </el-form-item>
       <el-form-item
          label="品牌名称"
          prop="name"
          style="margin-bottom: 20px"
        >
          <el-input type="text" v-model="form.name"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          @click="canle"
          >取消</el-button
        >
        <el-button
          type="primary"
          @click="submit"
          >确定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
import api from '@/api'
export default {
  name: "brand",
  components: {
    //HelloWorld
  },
  data() {
    return {
      params:{
        name:"",//模糊查询 name字段
        pageNum:1,
        pageSize:5
      },
      rows:[],
      total:0,
      dialogFormVisible:false,
      form:{
        _id:0,
        img:'',
        name:'',
      },
      rules:{
        img:[
           {required:true,message:'logo不能为空',trigger:'blur'}
        ],
        name:[
          {required:true,message:'品牌名称不能为空',trigger:'blur'}
        ],
      },
      selecteds:[]
    };
  },
  methods: {
    //触发文件打开 点击加号
    openFile() {
      let fileElement = this.$refs.file;
      fileElement.click();
    },
    //监听上传文件事件
    changeFile(e) {
      let files = e.target.files;
      let formData = new FormData();
      formData.append("file", files[0]);
      this.$http({
        url: "upload",
        method: "POST",
        data: formData,
      }).then((res) => {
        if(res.filename)this.form.img = api.baseURL+'/uploads/'+ res.filename
        console.log(this.form)
      });
    },
    //关闭弹窗前的回调
     handleClose(done) {
        this.$confirm('确认关闭？')
          .then(() => {
            this.getList(1)
            done();
          })
          .catch(() => {
          });
      },
    //取消弹窗刷新列表
    canle(){
      this.dialogFormVisible = false;
      this.getList(1)
    },
    //获取列表
    getList(pageNum){
      if(pageNum)this.params.pageNum = pageNum
      this.$http({
        url:'/admin/index/brand',
        params:this.params
      }).then(res=>{
        console.log(res)
        this.total = res.total
        this.rows = res.rows
    })
    },
  
    removeMore(){
      //获取选中的数据
      let checkedRowsPromse = []
      let success = [] ,fail = []
      for(let i = 0 ; i<this.selecteds.length;i ++){
        checkedRowsPromse.push(
          new Promise(resovle =>{
            let row = this.selecteds[i]
             this.$http({
              url:'/admin/index/brand',
              method:'DELETE',
              params:{indexId:row._id}
            }).then(res =>{
              if(!res.errorMsg){
                success.push(row._id)
              }else{
                fail.push(row._id)
              }
              resovle()
            })
            })
        )
      }
      ///删除
      Promise.all(checkedRowsPromse).then(()=>{
        this.$message({
          message:`批量删除完成，成功删除${success.length}条数据，删除失败${fail.length}条数据`,
          duration:3000
        });
        this.getList(1)
      })
    },
    //编辑时取消按钮改变页面显示值 解决办法 点击取消时 重新渲染一次页面
    cancel(){
      this.getList(1)
      this.dialogFormVisible=false
    },
    handleSelectionChange(rows){
        //存储选中数据
      this.selecteds = rows
    },
    //修改pagesize
    sizeChange(pageSize){
      this.params.pageSize=pageSize
      this.getList(1)
    },
    add(){
      //初始化
      this.form ={
        _id:0,
        img:'',
        name:'',
      }
      this.dialogFormVisible=true
    },
    edit(row){
      this.form = row
      this.dialogFormVisible = true
    },
    //删除
    remove(row){
      console.log(row)
      this.$http({
        url:'/admin/index/brand',
        method:'DELETE',
        params:{indexId:row._id}
      }).then(res =>{
        if(!res.errorMsg){
          this.getList(1)
        }
      })
    },
    submit(){
       this.$refs.form.validate((valid) => {
         console.log(this.form)
         if(valid){
           this.form.indexId = this.form._id
           this.$http({
             url:'/admin/index/brand',
             method:this.form.indexId ? 'PUT':'POST',//通过indeid判断是新增还是编辑
             data:this.form
           }).then(res =>{
             if(!res.errorMsg){
               this.dialogFormVisible = false
                this.getList(this.form.indexId ? undefined :1)
             }
           })
         }
       })
    }
  },

               
 
  created() {
    this.getList()
     
   
  },
  mounted() {

  },
};
</script>

<style >

</style>
